package v1

import (
	"github.com/Unknwon/com"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"hytx_media/models"
	"hytx_media/pkg/app"
	"hytx_media/pkg/e"
	"hytx_media/pkg/logging"
	"hytx_media/pkg/setting"
	"hytx_media/pkg/util"
	"hytx_media/service/article_service"
	"net/http"
)

// 查看文章列表

func GetArticles(c *gin.Context) {
	appG := app.Gin{c}
	userId := c.MustGet("user").(*models.MediaUser).ID
	valid := validation.Validation{}
	// 查询条件
	var title string
	if arg := c.Query("title"); arg != "" {
		title = arg
	}

	status := -1
	if arg := c.Query("status"); arg != "" {
		status = com.StrTo(arg).MustInt()
		valid.Min(status, 1, "status").Message("标签必须大于0！")
	}
	var beginTime string
	if begin := c.Query("begin_time"); begin != "" {
		beginTime = begin
	}

	var endTime string
	if end := c.Query("end_time"); end != "" {
		endTime = end
	}

	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
		return
	}
	logging.Info(beginTime,endTime)
	articleService := article_service.Article{
		Status:    status,
		Title:     title,
		Author:    userId,
		BeginTime: beginTime,
		EndTime:   endTime,
		PageNum:   util.GetPage(c),
		PageSize:  setting.AppSetting.PageSize,
	}

	total, err := articleService.Count()

	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_GET_ARTICLES_FAIL, nil)
		return
	}
	article, err := articleService.GetAll()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_GET_ARTICLES_FAIL, nil)
		return
	}
	var pageNum int
	if total < 10 {
		pageNum = 1
	} else {
		pageNum = total / 10
	}
	data := make(map[string]interface{})
	data["lists"] = article
	data["total"] = total
	data["pageNum"] = pageNum
	data["page"] = c.Query("page")
	appG.Response(http.StatusOK, e.SUCCESS, data)
}

// 查看单个文章
func GetArticle(c *gin.Context) {
	appG := app.Gin{c}
	id := com.StrTo(c.Param("id")).MustInt()
	valid := validation.Validation{}

	valid.Min(id, 1, "id").Message("ID必须大于1")
	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
		return
	}
	articleService := article_service.Article{ID: id}
	exists, err := articleService.ExistByID()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_CHECK_EXIST_ARTICLE_FAIL, nil)
		return
	}
	if !exists {
		appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_ARTICLE, nil)
		return
	}

	article, err := articleService.Get()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_GET_ARTICLE_FAIL, nil)
		return
	}
	appG.Response(http.StatusOK, e.SUCCESS, article)
}

//添加文章
func AddArticle(c *gin.Context) {
	appG := app.Gin{c}
	title := c.PostForm("title")
	labelId := c.PostForm("label_id")
	content := c.PostForm("content")
	coverPath := c.PostForm("cover_path")
	isAd := com.StrTo(c.PostForm("is_ad")).Exist()
	ArticleCategoryId := com.StrTo(c.PostForm("article_category_id")).MustInt()
	status := com.StrTo(c.PostForm("status")).MustInt()
	sort := 1
	// 获取当前登陆的自媒体账号id
	author := c.MustGet("user").(*models.MediaUser)
	if author.Status != 3 {
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg" : "你还未通过审核",
		})
		return
	}
	//敏感词检测
	//if bad := badword.Find(title); len(bad) > 0 {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"code" : 400,
	//		"msg" : "标题含有敏感词汇{" + strings.Replace(strings.Trim(fmt.Sprint(bad), "[]"), " ", ",", -1) + "}",
	//	})
	//	return
	//}
	////敏感词检测
	//if bad := badword.Find(content); len(bad) > 0 {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"code" : 400,
	//		"msg" : "内容含有敏感词汇{" + strings.Replace(strings.Trim(fmt.Sprint(bad), "[]"), " ", ",", -1) + "}",
	//	})
	//	return
	//}
	authorId := author.ID
	logging.Info("media_user", authorId)
	valid := validation.Validation{}
	valid.Required(title, "title").Message("标题不能为空！")
	valid.Required(labelId, "label_id").Message("标签不能为空！")
	valid.Required(content, "content").Message("内容不能为空！")
	valid.Required(status, "status").Message("状态不能为空！")
	//valid.Required(coverPath, "cover_path").Message("文章封面不能为空")
	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusOK, e.INVALID_PARAMS, valid.Errors)
		return
	}

	articleService := article_service.Article{
		Title:             title,
		LabelId:           labelId,
		Content:           content,
		Cover:             coverPath,
		ArticleCategoryId: ArticleCategoryId,
		IsAd:              isAd,
		Sort:              sort,
		Author:            authorId,
		Status:            status,
	}
	if err := articleService.Add(); err != nil {
		appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
		return
	}
	appG.ResponseMsg(http.StatusOK, "插入文章成功！", nil)

}

// 修改文章
func EditArticle(c *gin.Context) {
	author := c.MustGet("user").(*models.MediaUser)
	if author.Status != 3 {
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg" : "你还未通过审核",
		})
		return
	}
	appG := app.Gin{c}
	valid := validation.Validation{}
	id := com.StrTo(c.Param("id")).MustInt()
	title := c.PostForm("title")
	labelId := c.PostForm("label_id")
	content := c.PostForm("content")
	coverPath := c.PostForm("cover_path")
	isAd := com.StrTo(c.PostForm("is_ad")).Exist()
	ArticleCategoryId := com.StrTo(c.PostForm("article_category_id")).MustInt()
	status := com.StrTo(c.PostForm("status")).MustInt()
	operateStatus := com.StrTo(c.PostForm("operate_status")).MustInt()
	valid.Min(id, 1, "id").Message("id必须大于1")
	valid.MaxSize(title, 50, "title").Message("标题最长50个字符")
	valid.Required(content, "content").Message("内容不能为空！")
	//valid.Required(coverPath, "cover_path").Message("文章封面不能为空!")
	valid.Required(ArticleCategoryId, "article_category_id").Message("需要选择文章分类！")

	if valid.HasErrors() {
		appG.Response(http.StatusOK, e.INVALID_PARAMS, valid.Errors)
		return
	}
	//敏感词检测
	//if bad := badword.Find(title); len(bad) > 0 {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"code" : 400,
	//		"msg" : "标题含有敏感词汇{" + strings.Replace(strings.Trim(fmt.Sprint(bad), "[]"), " ", ",", -1) + "}",
	//	})
	//	return
	//}
	////敏感词检测
	//if bad := badword.Find(content); len(bad) > 0 {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"code" : 400,
	//		"msg" : "内容含有敏感词汇{" + strings.Replace(strings.Trim(fmt.Sprint(bad), "[]"), " ", ",", -1) + "}",
	//	})
	//	return
	//}
	logging.Info("operateStatus", operateStatus)
	articleService := article_service.Article{
		ID:                id,
		Title:             title,
		LabelId:           labelId,
		Content:           content,
		Cover:             coverPath,
		ArticleCategoryId: ArticleCategoryId,
		IsAd:              isAd,
		Status:            status,
		OperateStatus:     operateStatus,
	}
	exists, err := articleService.ExistByID()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_CHECK_EXIST_ARTICLE_FAIL, nil)
		return
	}
	if !exists {
		appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_ARTICLE, nil)
		return
	}

	err = articleService.Edit()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_EDIT_ARTICLE_FAIL, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, "修改成功！")

}

// 删除文章

func DeleteArticle(c *gin.Context) {
	appG := app.Gin{c}

	valid := validation.Validation{}
	id := com.StrTo(c.Param("id")).MustInt()

	valid.Min(id, 1, "id").Message("id必须大于1！")

	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusOK, e.INVALID_PARAMS, valid.Errors)
		return
	}

	articleService := article_service.Article{ID: id}

	exists, err := articleService.ExistByID()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_CHECK_EXIST_ARTICLE_FAIL, nil)
		return
	}
	if !exists {
		appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_ARTICLE, nil)
		return
	}

	err = articleService.Deleted()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_DELETE_ARTICLE_FAIL, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, nil)

}

// 撤回文章
func RevokeArticle(c *gin.Context) {
	appG := app.Gin{c}

	valid := validation.Validation{}
	id := com.StrTo(c.Param("id")).MustInt()
	status := com.StrTo(c.PostForm("status")).MustInt()
	operateStatus := com.StrTo(c.PostForm("operate_status")).MustInt()
	valid.Min(id, 1, "id").Message("id必须大于1！")
	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusOK, e.INVALID_PARAMS, valid.Errors)
		return
	}

	articleService := article_service.Article{
		ID:            id,
		Status:        status,
		OperateStatus: operateStatus,
	}

	exists, err := articleService.ExistByID()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_CHECK_EXIST_ARTICLE_FAIL, nil)
		return
	}
	if !exists {
		appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_ARTICLE, nil)
		return
	}

	err = articleService.Revoke()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_DELETE_ARTICLE_FAIL, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, nil)

}

//统计操作次数

func SumArticleOperaNum(c *gin.Context) {
	appG := app.Gin{c}
	userId := c.MustGet("user").(*models.MediaUser).ID
	//var (
	//actual_pageviews int // 实际浏览量
	//comment_num   int // 评论数量
	//share_num int // 分享数量
	//recommend_num int // 推荐数量
	//collect_num int // 收藏数量
	//)
	articleService := article_service.Article{ID: userId}
	actualPageviews, err := articleService.SumOperaNum("actual_pageviews")
	if err != nil {
		appG.ResponseMsg(http.StatusOK, "", nil)
		return
	}
	commentNum, err := articleService.SumOperaNum("comment_num")

	if err != nil {
		appG.ResponseMsg(http.StatusOK, "", nil)
		return
	}
	shareNum, err := articleService.SumOperaNum("share_num")
	if err != nil {
		appG.ResponseMsg(http.StatusOK, "", nil)
		return
	}
	recommendNum, err := articleService.SumOperaNum("recommend_num")
	if err != nil {
		appG.ResponseMsg(http.StatusOK, "", nil)
		return
	}
	collectNum, err := articleService.SumOperaNum("collect_num")
	if err != nil {
		appG.ResponseMsg(http.StatusOK, "", nil)
		return
	}
	data := make(map[string]interface{})
	data["actual_pageviews"] = actualPageviews
	data["comment_num"] = commentNum
	data["share_num"] = shareNum
	data["recommend_num"] = recommendNum
	data["actual_pageviews"] = actualPageviews
	data["collect_num"] = collectNum
	appG.Response(http.StatusOK, e.SUCCESS, data)
}
